<?php
namespace Api\Controller;
use Think\Controller;
class QrcodeController extends CommonController {
	private function getAccessToken(){
		$map['wid'] = session("wid");
		$info = M("Wechat")->where($map)->find();

		if(date("Y-m-d H:i:s") < $info['token_end_time']){
            return $info['authorizer_access_token'];
        }else{
            $token = $this->get_component_access_token();
            $url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token={$token}";

            $post_data = array(
                "component_appid"=>C("OPEN_APPID"),
                "authorizer_appid"=>$info['appid'],
                "authorizer_refresh_token"=>$info['authorizer_refresh_token']);
            $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
            $res = $this->ihttp_post($url, $json);
            $td = json_decode($res, true);
            if($td['authorizer_access_token']){
                $map['wid'] = $info['wid'];
                $data['authorizer_access_token'] = $td['authorizer_access_token'];
                $data['authorizer_refresh_token'] = $td['authorizer_refresh_token'];
                $data['token_end_time'] = date("Y-m-d H:i:s", time()+$td['expires_in']-60);
                M("Wechat")->where($map)->save($data);
                return $td['authorizer_access_token'];
            }else{
                // dump($td);
                // $this->error($td['errmsg']);
                // $this->reAuth();
                exit("网络忙！");
            }
        }
	}

	private function get_component_access_token(){
        $token = S("component_access_token");
        if($token){
            return $token;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";

        $post_data = array(
            "component_appid"=>C("OPEN_APPID"),
            "component_appsecret"=>C("OPEN_APPSECRET"),
            "component_verify_ticket"=>S("component_verify_ticket"));
        $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);
        $td = json_decode($res, true);
        if($td['component_access_token']){
            S("component_access_token", $td['component_access_token'], $td['expires_in'] - 120);
            return $td['component_access_token'];
        }else{
            return false;
        }
    }

	public function getOrderWxaCode(){
		$access_token = $this->getAccessToken();

		$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
		$post_data = array(
			'scene'=>$_GET['out_trade_no'].",".session('wid'),
			'page'=>'pages/mine/shop/yan/list'
		);
		$json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);
        header('Content-type: image/JPEG');
        echo $res;
        // dump($res);
	}
    public function getShopWxaCode(){
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
        // dump($url);
        $type = M('shop')->where(array('shop_id'=>$_GET['shop_id']))->getField('type');
        if(empty($type)){
            $page = 'pages/shop/detail';
        }else{
            $page = 'pages/shop/'.$type.'/detail';
        }
        $post_data = array(
            'scene'=>$_GET['shop_id'],
            'page'=>$page
        );
        $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);

        header('Content-type: image/JPEG');
       // echo $res;
        $shop = M('shop')->where(array('shop_id'=>$_GET['shop_id']))->find();
        $img = $this->shopQrcode($shop['logo_url'],$res,I("shop_id"));
        $this->ajaxReturn($img);
    }

    public function getShopWxaCode2(){
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
        // dump($url);
        $type = M('shop')->where(array('shop_id'=>$_GET['shop_id']))->getField('type');
        if(empty($type)){
            $page = 'pages/shop/detail';
        }else{
            $page = 'pages/shop/'.$type.'/detail';
        }
        $post_data = array(
            'scene'=>$_GET['shop_id'],
            'page'=>$page
        );
        $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);

        header('Content-type: image/JPEG');
        echo $res;
//        $shop = M('shop')->where(array('shop_id'=>$_GET['shop_id']))->find();
//        $img = $this->shopQrcode($shop['logo_url'],$res,I("shop_id"));
//        $this->ajaxReturn($img);
    }
    //获取二维码
    public function getPayCode(){
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={$access_token}";

        //获取随机数字
        $billno = date('YmdHis') .mt_rand(100000,999999);
        $data['num'] = $billno;
        $eq['wid'] = session('wid');
        $eq['id'] = $_GET['card_id'];
        $mycard = M('shop_mycard')->where($eq)->find();
        $data['openid'] = $mycard['openid'];
        $data['shop_id'] = $mycard['card_id'];
        $data['wid'] = session('wid');
        $data['mycard_id'] = $_GET['card_id'];
        $data['create_time'] = time();
        $data['end_time'] = time() + 60;
        M('shop_qrcode') ->add($data);

        $page = 'pages/mine/shop/mycard/pay?num='.$billno.'&card_id='.$_GET['card_id'];

        $post_data = array(
            'width'=>430,
            'path'=>$page
        );
        $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);
        echo $res;

        $this->ajaxReturn($res);

    }
    //保存支付二维码
    public function payQrcode($shopimg,$qrcode,$shop_id){
        define('PATH', "");
        //判断是否已经生成小程序码.如果有，直接返回无需再生成
        $shop = M('shop')->where(['shop_id'=>$shop_id])->find();
        if($shop['qrcode'] && file_exists('qrcode/pay'.session('wid')."/".$shop_id.'.png')){
            $arr = array('ret'=>1,
                'msg'=>'success',
                'data'=>array('url'=>'https://www.58zltc.com/qrcode/pay'.session('wid')."/".$shop_id.'.png'),     //处理完的新小程序码 保存在服务器，传回地址给小程序端即可
            );
            return $arr;
            exit;
        }
        //店铺没有logo则用平台的。

            //处理小程序码路径
            $file_code_name = $shop_id.".png";
            file_put_contents(PATH.$file_code_name,$qrcode);//保存到本地
            $this->moveFile(PATH.$file_code_name,'qrcode/pay'.session('wid')."/".PATH.$file_code_name,true);
            $this->unlinkFile(PATH.$file_code_name);
            $arr = array('ret'=>1,
                'msg'=>'success',
                'data'=>array('url'=>'https://www.58zltc.com/qrcode/pay'.session('wid')."/".PATH.$file_code_name),     //处理完的新小程序码 保存在服务器，传回地址给小程序端即可
            );
            return $arr;
            exit;

    }


    //店铺小程序码
    public function shopQrcode($shopimg,$qrcode,$shop_id)
    {
        define('PATH', "");
        //判断是否已经生成小程序码.如果有，直接返回无需再生成
        $shop = M('shop')->where(['shop_id'=>$shop_id])->find();
        if($shop['qrcode'] && file_exists('qrcode/'.session('wid')."/".$shop_id.'.png')){
            $arr = array('ret'=>1,
                'msg'=>'success',
                'data'=>array('url'=>$shop['qrcode']),     //处理完的新小程序码 保存在服务器，传回地址给小程序端即可
            );
            return $arr;
            exit;
        }
        //店铺没有logo则用平台的。
        if(!$shop['logo_url']){
            //处理小程序码路径
            $file_code_name = $shop_id.".png";
            file_put_contents(PATH.$file_code_name,$qrcode);//保存到本地
            $this->moveFile(PATH.$file_code_name,'qrcode/'.session('wid')."/".PATH.$file_code_name,true);
            $this->unlinkFile(PATH.$file_code_name);
            $arr = array('ret'=>1,
                'msg'=>'success',
                'data'=>array('url'=>'https://www.58zltc.com/qrcode/'.session('wid')."/".PATH.$file_code_name),     //处理完的新小程序码 保存在服务器，传回地址给小程序端即可
            );
            return $arr;
            exit;
        }
        //var_dump(file_exists($shop['logo_url']));exit;
        //处理小程序码路径
        $file_code_name = $shop_id."qrcode.png";
        file_put_contents(PATH.$file_code_name,$qrcode);//保存到本地

        //处理店铺logo
        $imgg = $this->yuan_img($shop['logo_url']);     //yuan_img() 方法在文末会列出
        $file_name = $shop_id."shop.png";
        imagepng($imgg,PATH.$file_name);
        imagedestroy($imgg);
        //缩小头像
        $target_im = imagecreatetruecolor(192,192);     //创建一个新的画布（缩放后的），从左上角开始填充透明背景
        imagesavealpha($target_im, true);
        $trans_colour = imagecolorallocatealpha($target_im, 0, 0, 0, 127);
        imagefill($target_im, 0, 0, $trans_colour);

        $o_image = imagecreatefrompng(PATH.$file_name);   //获取上文已保存的修改之后头像的内容
        $wh  = getimagesize(PATH.$file_name);
        $w   = $wh[0];
        $h   = $wh[1];
        $w   = min($w, $h);
        $h   = $w;
        imagecopyresampled($target_im,$o_image, 0, 0,0, 0, 192, 192, $w, $h);
        $file_head_name = "23".time().".png";
        $comp_path =PATH.$file_head_name;
        imagepng($target_im,$comp_path);
        imagedestroy($target_im);

        //传入保存后的二维码地址
        $url = $this->create_pic_watermark(PATH.$file_code_name,$comp_path,"center",$shop_id);

        $path = 'qrcode/'.session('wid')."/".$url;
        //将小程序码位置存到数据库
        M('shop')->where(['shop_id'=>$shop_id])->save(['qrcode'=>'https://www.58zltc.com/'.$path]);
        //移动文件位置，删除多余文件
        $this->moveFile($url,$path,true);
        $this->unlinkFile($file_code_name);
        $this->unlinkFile($file_name);
        $this->unlinkFile($comp_path);

        $arr = array('ret'=>1,
            'msg'=>'success',
            'data'=>array('url'=>'https://www.58zltc.com/'.$path),     //处理完的新小程序码 保存在服务器，传回地址给小程序端即可
        );
        //echo json_encode($arr);
        //$this->ajaxReturn($arr);
        return $arr;
    }
    /**
     * [create_pic_watermark 添加图片水印]  头像贴在二维码中间
     * @param  [string] $dest_image [需要添加图片水印的图片名]
     * @param  [string] $watermark  [水印图片名]
     * @param  [string] $locate     [水印位置，center,left_buttom,right_buttom三选一]
     * @return [type]             [description]
     */
    function create_pic_watermark($dest_image,$watermark,$locate,$shop_id){
        define('PATH', "/");
        list($dwidth,$dheight,$dtype)=getimagesize($dest_image);
        list($wwidth,$wheight,$wtype)=getimagesize($watermark);
        $types=array(1 => "GIF",2 => "JPEG",3 => "PNG",
            4 => "SWF",5 => "PSD",6 => "BMP",
            7 => "TIFF",8 => "TIFF",9 => "JPC",
            10 => "JP2",11 => "JPX",12 => "JB2",
            13 => "SWC",14 => "IFF",15 => "WBMP",16 => "XBM");
        $dtype=strtolower($types[$dtype]);//原图类型
        $wtype=strtolower($types[$wtype]);//水印图片类型
        $created="imagecreatefrom".$dtype;
        $createw="imagecreatefrom".$wtype;
        $imgd=$created($dest_image);
        $imgw=$createw($watermark);
        switch($locate){
            case 'center':
                $x=($dwidth-$wwidth)/2;
                $y=($dheight-$wheight)/2;
                break;
            case 'left_buttom':
                $x=1;
                $y=($dheight-$wheight-2);
                break;
            case 'right_buttom':
                $x=($dwidth-$wwidth-1);
                $y=($dheight-$wheight-2);
                break;
            default:
                die("未指定水印位置!");
                break;
        }
        imagecopy($imgd,$imgw,$x,$y,0,0, $wwidth,$wheight);
        $save="image".$dtype;
        //保存到服务器
        $f_file_name = $shop_id.".png";
        imagepng($imgd,PATH.$f_file_name); //保存
        imagedestroy($imgw);
        imagedestroy($imgd);
        //传回处理好的图片
        $url = PATH.$f_file_name;
        return $url;
    }

    /**
     * [yuan_img 编辑图片为圆形]  剪切头像为圆形
     * @param  [string] $imgpath [头像保存之后的图片名]
     */
    function yuan_img($imgpath) {
        $ext     = pathinfo($imgpath);
        $src_img = null;
        switch ($ext['extension']) {
            case 'jpg':
                $src_img = imagecreatefromjpeg($imgpath);
                break;
            case 'png':
                $src_img = imagecreatefromjpeg($imgpath);
                break;
            case 'jpeg':
                $src_img = imagecreatefromjpeg($imgpath);
                break;
        }
        $wh  = getimagesize($imgpath);
        $w   = $wh[0];
        $h   = $wh[1];
        $w   = min($w, $h);
        $h   = $w;
        $img = imagecreatetruecolor($w, $h);
        //这一句一定要有
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r   = $w / 2; //圆半径
        $y_x = $r; //圆心X坐标
        $y_y = $r; //圆心Y坐标
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
            }
        }
        return $img;
    }
    /**
     * 移动文件
     *
     * @param string $fileUrl
     * @param string $aimUrl
     * @param boolean $overWrite 该参数控制是否覆盖原文件
     * @return boolean
     */
    function moveFile($fileUrl, $aimUrl, $overWrite = false) {
        if (!file_exists($fileUrl)) {
            return false;
        }
        if (file_exists($aimUrl) && $overWrite = false) {
            return false;
        } elseif (file_exists($aimUrl) && $overWrite = true) {
            $this-> unlinkFile($aimUrl);
        }
        $aimDir = dirname($aimUrl);
        $this-> createDir($aimDir);
        rename($fileUrl, $aimUrl);
        return true;
    }
    /**
     * 删除文件
     *
     * @param string $aimUrl
     * @return boolean
     */
    function unlinkFile($aimUrl) {
        if (file_exists($aimUrl)) {
            unlink($aimUrl);
            return true;
        } else {
            return false;
        }
    }
    /**
     * 建立文件夹
     *
     * @param string $aimUrl
     * @return viod
     */
    function createDir($aimUrl) {
        $aimUrl = str_replace('', '/', $aimUrl);
        $aimDir = '';
        $arr = explode('/', $aimUrl);
        $result = true;
        foreach ($arr as $str) {
            $aimDir .= $str . '/';
            if (!file_exists($aimDir)) {
                $result = mkdir($aimDir);
            }
        }
        return $result;
    }

    //生成商品海报
    public function getGoodsPoster(){
        //如果有，直接返回无需再生成
//        $shop = M('goods')->where(['id'=>$_GET['goods_id']])->find();
//        if($shop['qrcode'] && file_exists('qrcode_goods_poster/'.$_GET['goods_id'].'.png')){
//            $arr = array('ret'=>1,
//                'msg'=>'success',
//                'data'=>array('url'=>'https://www.58zltc.com/qrcode_goods_poster/'.$_GET['goods_id'].'.png'),
//            );
//            $this->ajaxReturn($arr);
//            exit;
//        }
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
        $page = 'pages/shop/goods/detail';
        $post_data = array(
            'scene'=>$_GET['goods_id'],
            'page'=>$page
        );
        $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);
        header('Content-type: image/JPEG');

        $goods = M('goods')->where(array('id'=>$_GET['goods_id']))->find();
        $img = $this->goodsQrcode($goods['img_url'],$res,I("goods_id"));

        //生成海报
        $wechat    = M('wechat')->where(['wid' => $goods['wid']])->find();
        $shopInfo  = M('shop')->where(['shop_id' => $goods['shop_id']])->find();
        if (1) {
            $shop_logo = $shopInfo['logo_url'];
            $shop_name = $shopInfo['name'];
            $shop_from = $wechat['nick_name'];
            $goods_img = $goods['img_url'];
            $goods_title = $goods['title'];
            $goods_price = $goods['price'];
            $goods_price_old = $goods['old_price'];
            $QRcode = $img['data']['url'];
            $path = 'qrcode_goods_poster/'.$_GET['goods_id'].'.png';
            $this->createCircleImage ($shop_logo, $shop_name, $shop_from, $goods_img, $goods_title, $goods_price,
                $goods_price_old, $QRcode, $path, $_GET['goods_id']);
            $arr = array('ret'=>1,
                'msg'=>'success',
                'data'=>array('url'=>'https://www.58zltc.com/qrcode_goods_poster/'.$_GET['goods_id'].'.png'),
            );
            //
            M('goods')->where(['id' => $_GET['goods_id']])->save(['qrcode' => $arr['data']['url']]);
            $this->ajaxReturn($arr);
        }

    }

    //商品小程序码
    public function goodsQrcode($shopimg,$qrcode,$shop_id)
    {
        define('PATH', "");
        //处理小程序码路径
        $file_code_name = $shop_id.".png";
        file_put_contents(PATH.$file_code_name,$qrcode);//保存到本地
        $this->moveFile(PATH.$file_code_name,'qrcode_goods/'.session('wid')."/".PATH.$file_code_name,true);
        $this->unlinkFile(PATH.$file_code_name);
        $arr = array('ret'=>1,
            'msg'=>'success',
            'data'=>array('url'=>'https://www.58zltc.com/qrcode_goods/'.session('wid').'/'.$file_code_name),
        );
        return $arr;
    }

    /* 创建分享朋友圈海报
     *
     * $shop_logo       店铺logo
     * $shop_name       店铺名
     * $shop_from       来自xx平台
     * $goods_img       商品大图
     * $goods_title     商品名
     * $goods_price     商品价格
     * $goods_price_old 商品价格
     * $QRcode          分享二维码
     * $path            保存路径
     * $goods_id        商品id
     * */
    public function createCircleImage ($shop_logo, $shop_name, $shop_from, $goods_img, $goods_title, $goods_price,
                                $goods_price_old, $QRcode, $path, $goods_id) {
        $width  = 300;
        $height = 455;
        $image  = imagecreatetruecolor($width, $height);//底图
        $ext1     = substr($goods_img,strrpos($goods_img, '.') + 1);
        $gImage = null;
        switch ($ext1) {
            case 'jpg':
                $gImage = imagecreatefromjpeg($goods_img);
                break;
            case 'png':
                $gImage = imagecreatefrompng($goods_img);
                break;
            case 'jpeg':
                $gImage = imagecreatefromjpeg($goods_img);
                break;
        }
        $QImage = imagecreatefromstring(file_get_contents($QRcode));//小程序码
        //商品活动属性
        $good = M('goods')->where(['id' => $goods_id])->find();
        if ($good['is_pin'] == 1) {
            $kqImage = imagecreatefrompng('https://www.58zltc.com/Public/images/wx/pintuan_bg.png');
            list($kq_width, $kq_height) = getimagesize('https://www.58zltc.com/Public/images/wx/pintuan_bg.png');//拼团
        } else {
            $kqImage = imagecreatefrompng('https://www.58zltc.com/Public/images/wx/kuaiqiang_bg.png');
            list($kq_width, $kq_height) = getimagesize('https://www.58zltc.com/Public/images/wx/kuaiqiang_bg.png');//快抢
        }
        list($sl_width, $sl_height) = getimagesize($shop_logo);
        list($gi_width, $gi_height) = getimagesize($goods_img);
        list($q_width, $q_height) = getimagesize($QRcode);
        $white = imagecolorallocate($image, 255, 255, 255);
        $black = imagecolorallocate($image, 0, 0, 0);
        $hui   = imagecolorallocate($image, 150,150,150);
        $red   = imagecolorallocate($image, 255,0,0);
        imagefill($image, 0, 0, $white);
        //商品图片
        imagecopyresampled($image, $gImage, 0, 0, 0, 0, 300, 300, $gi_width, $gi_height);
        //活动
        imagecopyresampled($image, $kqImage, 0, 300, 0, 0, 300, 35, $kq_width, $kq_height);
        $goods_titles = mb_strimwidth($goods_title, 0, 27);
        if (mb_strlen($goods_title) > 30) $goods_titles .= '...';
        //商品名称
        imagettftext($image, 11, 0, 12, 377, $black, 'simhei.ttf', $goods_titles);
        //购买价
        imagettftext($image, 13, 0, 12, 410, $red, 'simhei.ttf', '购买价:');
        imagettftext($image, 13, 0, 80, 410, $red, 'simhei.ttf', '￥'.$goods_price);
        //原价
        imagettftext($image, 10, 0, 12, 430, $hui, 'simhei.ttf', '原价:');
        imagettftext($image, 10, 0, 50, 430, $hui, 'simhei.ttf', '￥'.$goods_price_old);
        imageline($image, 12, 425, 120, 425, $hui);
        //小程序码
        imagecopyresampled($image, $QImage, 186, 345, 0, 0, 100, 100, $q_width, $q_height);
        header("content-type: image/png");
        imagepng($image, $path);
        imagedestroy($image);
    }

    /*
     * 获取店员管理二维码
     *
     * */
    public function getClerkQrcode () {
        $access_token = $this->getAccessToken();

        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
        $post_data = array(
            'scene' => I('openid'),
            'page'  => 'pages/index/index'
        );
        $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);
        header('Content-type: image/JPEG');
        echo $res;
    }
}